package com.x.bpm.manage;

import com.x.bpm.dao.BpmDao;
import com.x.bpm.model.*;
import com.x.framework.bus.RuleEngine;
import com.x.framework.manage.BaseManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by x on 2017/11/13.
 */
@Service
public class BpmManage extends BaseManage {
    @Autowired
    private BpmDao bpmDao;

    public List<Operation> selectOperationList(StateMap stateMap, Rule rule) throws Exception {
//        List<StateEnum> stateEnumLis = bpmDao.selectInstanceStateEnumLis(instance);
//        Map<String, Object> map = new HashMap<String, Object>();
//        for (StateEnum stateEnum : stateEnumLis) {
//            map.put(stateEnum.getState().getStateKey(), stateEnum.getStateValue());
//        }
        Map<String, Object> map = stateMap.getMap();
        List<Rule> ruleList = bpmDao.selectRuleList(rule);
        String ruleIds = "";
        for (Rule r : ruleList) {
            if (RuleEngine.validateRule(map, r.getRuleExpress())) {
                ruleIds += "," + r.getRuleId();
            }
        }

        List<Operation> operationList = new ArrayList<Operation>();
        if (this.isNotNull(ruleIds)) {
            ruleIds = ruleIds.replaceFirst(",", "");
            operationList = bpmDao.selectOperationList(rule, ruleIds);
        }

        return operationList;
    }

    public void insertInstance(Instance instance, StateEnum ... stateEnums) throws Exception {
        Date date = this.getDate(0);
        instance.setInstanceCreateTime(date);
        Instance instanceDel = new Instance();
        instanceDel.setApplicationId(instance.getApplicationId());
        instanceDel.setInstanceId(instance.getInstanceId());

        for (StateEnum stateEnum : stateEnums) {
            instanceDel.setStateKey(stateEnum.getStateKey());
            this.delete(instanceDel);

            instance.setStateKey(stateEnum.getStateKey());
            instance.setStateValue(stateEnum.getStateValue());
            this.insert(instance);
        }
    }

    public static void main(String[] arg) throws Exception {
        String rule = "aState == 100 && bState == 200";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("aState", 200);
        map.put("bState", 200);
        System.out.println(RuleEngine.validateRule(map, rule));
    }
}
